function scrambled = bciScrambleEvents(s,maxSucc)
% scrambled = bciScrambleEvents(s,maxSucc)
% scrambles an event vector,
% s - event vector to scramble
% maxSucc (optional) - maximum number of successive equal elements (at
% least 2), for long vectors and/or small maxSucc this function may need 
% long time to find a solution

if nargin >1,
    retry = true;
    while retry,
    %fprintf('retry\n');        
        scrambled = s(randperm(length(s)));
        onsetSucc = find(diff([scrambled 0]));
        eventType = scrambled(onsetSucc);
        nSucc = diff([0 find(diff([scrambled 0]))]);
        while sum(nSucc>maxSucc)>0,
        %fprintf('reloop\n');              
            excMax = find(nSucc>maxSucc);
            if ~isempty(excMax),
                not = find(eventType==eventType(excMax(1)) & nSucc<maxSucc-1);
                if ~isempty(not),
                    nSucc(excMax(1))=nSucc(excMax(1))-1;
                    nSucc(not(1))=nSucc(not(1))+1;
                else
                    break;
                end
            end
        end
        if sum(nSucc>maxSucc)==0,
            retry = false;
        end
    end
    scrambled=zeros(size(s));
    newOnset=[0 cumsum(nSucc(1:end-1))]+1;
    for k=1:length(nSucc),
        scrambled(newOnset(k):newOnset(k)+nSucc(k)-1)=eventType(k);
    end
else
    scrambled = s(randperm(length(s)));    
end